#include "ImageCaptureThread.h"
#include <QImage>
#include <QDebug>
#include <opencv2/opencv.hpp>
ImageCaptureThread::ImageCaptureThread(void* cameraHandle, QObject *parent)
    : QThread(parent), m_hDevHandle(cameraHandle), m_isRunning(false)
{
}

ImageCaptureThread::~ImageCaptureThread()
{
    stopCapture();
}

void ImageCaptureThread::stopCapture()
{
    QMutexLocker locker(&m_mutex);
    if (m_isRunning) {
        m_isRunning = false;
        locker.unlock(); // 解锁后等待，避免死锁
        wait(); // 等待线程完全退出
    }
}

// 在run()函数中修正参数初始化
void ImageCaptureThread::run()
{
    m_isRunning = true;
    unsigned int nRecvBufSize = 0;
    MVCC_INTVALUE stParam = {0};
    int tempValue = MV_CC_GetIntValue(m_hDevHandle, "PayloadSize", &stParam);
    if (tempValue != 0) {
        emit errorOccurred("获取PayloadSize失败");
        return;
    }
    nRecvBufSize = stParam.nCurValue;
    unsigned char* pData = (unsigned char*)malloc(nRecvBufSize);
    if (!pData) {
        emit errorOccurred("内存分配失败（pData）");
        return;
    }

    MV_FRAME_OUT_INFO_EX stImageInfo = {0};

    int nRet = MV_CC_GetOneFrameTimeout(m_hDevHandle, pData, nRecvBufSize, &stImageInfo, 700);
    if (nRet != MV_OK) {
        free(pData);
        emit errorOccurred("初始获取图像失败，无法确定缓冲区大小");
        return;
    }

    // 根据目标像素格式（BGR8）计算所需缓冲区大小
    m_nBufSizeForSaveImage = stImageInfo.nWidth * stImageInfo.nHeight * 3; // 3字节/像素
    unsigned char* m_pBufForSaveImage = (unsigned char*)malloc(m_nBufSizeForSaveImage + 2048); // 额外预留空间
    if (!m_pBufForSaveImage) {
        free(pData);
        emit errorOccurred("内存分配失败（m_pBufForSaveImage）");
        return;
    }

    cv::Mat getImage; // 改用栈对象，避免动态内存管理问题
    while(m_isRunning) {
        nRet = MV_CC_GetOneFrameTimeout(m_hDevHandle, pData, nRecvBufSize, &stImageInfo, 700);
        if (nRet == MV_OK) {
            bool isMono = false;
            switch (stImageInfo.enPixelType) {
            case PixelType_Gvsp_Mono8:
            case PixelType_Gvsp_Mono10:
            case PixelType_Gvsp_Mono10_Packed:
            case PixelType_Gvsp_Mono12:
            case PixelType_Gvsp_Mono12_Packed:
                isMono = true;
                break;
            default:
                isMono = false;
                break;
            }

            if (isMono) {
                getImage = cv::Mat(stImageInfo.nHeight, stImageInfo.nWidth, CV_8UC1, pData);
                cv::cvtColor(getImage, getImage, cv::COLOR_GRAY2RGB); // 转为RGB
                QImage qImg(getImage.data, getImage.cols, getImage.rows, getImage.step, QImage::Format_RGB888);
                emit imageCaptured(qImg.copy());
            } else {
                MV_CC_PIXEL_CONVERT_PARAM stConvertParam = {0};
                stConvertParam.nWidth = stImageInfo.nWidth;
                stConvertParam.nHeight = stImageInfo.nHeight;
                stConvertParam.pSrcData = pData;
                stConvertParam.nSrcDataLen = stImageInfo.nFrameLen;
                stConvertParam.enSrcPixelType = stImageInfo.enPixelType;
                stConvertParam.enDstPixelType = PixelType_Gvsp_BGR8_Packed;
                stConvertParam.pDstBuffer = m_pBufForSaveImage;
                stConvertParam.nDstBufferSize = m_nBufSizeForSaveImage;

                // 检查转换结果并输出详细错误
                int convertRet = MV_CC_ConvertPixelType(m_hDevHandle, &stConvertParam);
                if (convertRet == MV_OK) {
                    getImage = cv::Mat(stImageInfo.nHeight, stImageInfo.nWidth, CV_8UC3, m_pBufForSaveImage);
                    cv::cvtColor(getImage, getImage, cv::COLOR_BGR2RGB);
                    QImage qImg(getImage.data, getImage.cols, getImage.rows, getImage.step, QImage::Format_RGB888);
                    emit imageCaptured(qImg.copy());
                } else {
                    // 输出具体错误码，便于排查（参考相机SDK错误码说明）
                    emit errorOccurred(QString("像素格式转换失败，错误码: %1，源格式: %2，目标格式: %3")
                                           .arg(convertRet)
                                           .arg(stImageInfo.enPixelType)
                                           .arg(PixelType_Gvsp_BGR8_Packed));
                }
            }
        } else {
            emit errorOccurred(QString("获取图像失败，错误码: %1").arg(nRet));
            msleep(10);
        }
    }

    // 释放资源
    free(pData);
    free(m_pBufForSaveImage);
}
